package com.joinway.framework.admin.core.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.joinway.framework.admin.core.type.Platform;
import com.joinway.framework.core.repository.SystemConfigRepository;
import com.joinway.framework.jpush.service.AndroidPushService;
import com.joinway.framework.jpush.service.IosPushService;
import com.joinway.framework.jpush.service.JPushService;

@Component
public class JPushServiceFactory implements ApplicationContextAware {

	private static ApplicationContext ctx;
	
	public static JPushService getInstance(Platform platform) throws Exception {
		SystemConfigRepository systemRepository = ctx.getBean(SystemConfigRepository.class);
		
		JPushService service = null;
		
		if(Platform.Android == platform){
			String androidMasterSecret = systemRepository.getStringValue(SystemConfigRepository.AndroidPushMasterKey);
			String androidAppKey = systemRepository.getStringValue(SystemConfigRepository.AndroidPushKey);
	
			if(StringUtils.isNotBlank(androidMasterSecret) && StringUtils.isNotBlank(androidAppKey)){
				service = new AndroidPushService(androidMasterSecret, androidAppKey);
			}
		}else{
			String iosMasterSecret = systemRepository.getStringValue(SystemConfigRepository.IosPushMasterKey);
			String iosAppKey = systemRepository.getStringValue(SystemConfigRepository.IosPushKey);
	
			if(StringUtils.isNotBlank(iosMasterSecret) && StringUtils.isNotBlank(iosAppKey)){
				service = new IosPushService(iosMasterSecret, iosAppKey);
			}	
		}
		
		return service;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		ctx = applicationContext;
	}
}
